<template>
  <div class="my-books">
    <NavBar />
    <main class="container">
      <h1>我的书籍</h1>
      
      <div class="user-actions">
        <router-link to="/publish" class="btn-publish">发布新书籍</router-link>
        <router-link to="/transactions" class="btn-transactions">我的交易记录</router-link>
        <button @click="reloadData" class="btn-reload">刷新数据</button>
      </div>
      
      <div class="tabs">
        <button 
          class="tab-btn" 
          :class="{ active: activeTab === 'selling' }"
          @click="changeTab('selling')"
        >
          在售书籍
        </button>
        <button 
          class="tab-btn" 
          :class="{ active: activeTab === 'sold' }"
          @click="changeTab('sold')"
        >
          已售出
        </button>
        <button 
          class="tab-btn" 
          :class="{ active: activeTab === 'removed' }"
          @click="changeTab('removed')"
        >
          已下架
        </button>
        <button 
          class="tab-btn" 
          :class="{ active: activeTab === 'purchased' }"
          @click="changeTab('purchased')"
        >
          已购买
        </button>
        <button 
          class="tab-btn" 
          :class="{ active: activeTab === 'favorite' }"
          @click="changeTab('favorite')"
        >
          收藏夹
        </button>
      </div>
      
      <LoadingSpinner v-if="isLoading" message="加载书籍数据..." />
      
      <transition v-else name="fade" mode="out-in">
        <div class="books-grid" v-if="filteredBooks.length > 0" :key="activeTab">
          <div class="book-card" v-for="book in filteredBooks" :key="book.id">
            <div class="book-cover">
              <img :src="getCoverUrl(book)" :alt="book.title">
              <div class="book-actions">
                <!-- 在售书籍的操作 -->
                <template v-if="activeTab === 'selling'">
                  <button @click="editBook(book.id)">编辑</button>
                  <button @click="deleteBook(book.id)" class="delete">下架</button>
                  <button @click="viewBookDetails(book.id)">查看</button>
                </template>
                
                <!-- 已售出书籍的操作 -->
                <template v-else-if="activeTab === 'sold'">
                  <button @click="viewBookDetails(book.id)">查看</button>
                </template>
                
                <!-- 已购买书籍的操作 -->
                <template v-else-if="activeTab === 'purchased'">
                  <button @click="viewBookDetails(book.book_id)">查看</button>
                </template>
                
                <!-- 已下架书籍的操作 -->
                <template v-else-if="activeTab === 'removed'">
                  <button @click="viewBookDetails(book.id)">查看</button>
                </template>
                
                <!-- 收藏夹书籍的操作 -->
                <template v-else-if="activeTab === 'favorite'">
                  <button @click="viewBookDetails(book.id)">查看</button>
                  <button @click="removeFavorite(book.id)" class="delete">
                    <el-icon class="star-icon"><star-filled /></el-icon>
                    取消收藏
                  </button>
                </template>
              </div>
            </div>
            <div class="book-info">
              <h3>{{ book.title }}</h3>
              <p class="book-author">{{ book.author }}</p>
              <p class="book-price">¥{{ book.price }}</p>
              
              <!-- 针对不同标签页显示不同信息 -->
              <template v-if="activeTab === 'selling'">
                <p class="book-status" v-if="book.status">{{ getStatusText(book.status) }}</p>
                <p class="book-views" v-if="book.views">浏览量: {{ book.views }}</p>
              </template>
              
              <template v-else-if="activeTab === 'sold'">
                <p class="book-date">售出时间: {{ formatDate(book.updated_at || book.sold_time) }}</p>
              </template>
              
              <template v-else-if="activeTab === 'purchased'">
                <p class="book-date">购买时间: {{ formatDate(book.created_at) }}</p>
              </template>
              
              <template v-else-if="activeTab === 'removed'">
                <p class="book-date">下架时间: {{ book.removedDate ? formatDate(book.removedDate) : formatDate(book.updated_at) }}</p>
                <p class="book-seller">卖家: {{ book.seller_name || book.seller || '未知' }}</p>
              </template>
              
              <template v-else-if="activeTab === 'favorite'">
                <p class="book-seller">卖家: {{ book.seller }}</p>
              </template>
            </div>
          </div>
        </div>
        
        <div class="empty-state" v-else :key="'empty-'+activeTab">
          <div class="empty-icon">📚</div>
          <h3>暂无{{ getEmptyStateText() }}</h3>
          <p v-if="activeTab === 'selling'">发布你的第一本二手书，开始交易吧！</p>
          <p v-else-if="activeTab === 'favorite'">浏览书籍并添加到收藏夹</p>
          <p v-else>去首页发现更多好书</p>
          <div class="empty-actions">
            <router-link to="/publish" class="btn-primary" v-if="activeTab === 'selling'">发布书籍</router-link>
            <router-link to="/" class="btn-secondary">浏览书籍</router-link>
          </div>
        </div>
      </transition>
    </main>
    
    <div class="confirm-dialog" v-if="showDeleteConfirm">
      <div class="dialog-content">
        <h3>确认删除</h3>
        <p>你确定要删除这本书籍吗？此操作不可撤销。</p>
        <div class="dialog-actions">
          <button class="btn-cancel" @click="showDeleteConfirm = false">取消</button>
          <button class="btn-confirm" @click="confirmDelete">确认删除</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import NavBar from '../components/NavBar.vue'
import LoadingSpinner from '../components/LoadingSpinner.vue'
import api from '@/api/apiClient'
import defaultCover from '@/assets/OIP.jpg'
import { StarFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const router = useRouter()
const route = useRoute()
const activeTab = ref('selling')
const publishedBooks = ref([])
const favoriteBooks = ref([])
const soldBooks = ref([])
const purchasedBooks = ref([])
const removedBooks = ref([])
const showDeleteConfirm = ref(false)
const bookToDelete = ref(null)
const isLoading = ref(true)

// 监听URL参数变化
watch(() => route.query.tab, (newTab) => {
  if (newTab && ['selling', 'sold', 'purchased', 'removed', 'favorite'].includes(newTab)) {
    activeTab.value = newTab
  }
}, { immediate: true })

onMounted(() => {
  // 如果URL中包含tab参数，则设置activeTab
  if (route.query.tab && ['selling', 'sold', 'purchased', 'removed', 'favorite'].includes(route.query.tab)) {
    activeTab.value = route.query.tab
  }
  
  loadData()
})

const loadData = async () => {
  isLoading.value = true
  try {
    console.log('开始加载我的书籍数据');
    await Promise.all([
      fetchPublishedBooks(),
      fetchFavoriteBooks(),
      fetchSoldBooks(),
      fetchPurchasedBooks(),
      fetchRemovedBooks()
    ])
    console.log('所有书籍数据加载完成，开始处理封面...');
    
    // 预加载所有活跃标签页的图片
    await preloadCovers();
  } finally {
    isLoading.value = false
    console.log('标签页:', activeTab.value, '书籍数量:', filteredBooks.value.length);
  }
}

const fetchPublishedBooks = async () => {
  try {
    // 调用API获取用户发布的书籍
    const response = await api.book.getMyBooks({ status: 'active' })
    
    // 处理响应数据
    if (Array.isArray(response)) {
      publishedBooks.value = response
    } else if (response && response.code === 200 && response.data) {
      publishedBooks.value = response.data
    } else {
      console.error('获取用户发布书籍失败: 返回格式不正确', response)
      publishedBooks.value = []
    }
    
    console.log('获取用户发布书籍成功:', publishedBooks.value)
  } catch (error) {
    console.error('获取用户发布书籍失败:', error)
    publishedBooks.value = []
  }
}

const fetchFavoriteBooks = async () => {
  try {
    // 调用API获取用户收藏的书籍
    const response = await api.favorite.getFavoriteBooks()
    
    // 处理响应数据
    if (Array.isArray(response)) {
      favoriteBooks.value = response
    } else if (response && response.code === 200 && response.data) {
      favoriteBooks.value = response.data
    } else {
      console.error('获取用户收藏书籍失败: 返回格式不正确', response)
      favoriteBooks.value = []
    }
    
    console.log('获取用户收藏书籍成功:', favoriteBooks.value)
  } catch (error) {
    console.error('获取用户收藏书籍失败:', error)
    favoriteBooks.value = []
  }
}

const fetchSoldBooks = async () => {
  try {
    // 调用API获取用户已售出的书籍（使用getMyBooks接口，筛选已售出状态）
    const response = await api.book.getMyBooks({ status: 'sold' })
    
    // 处理响应数据
    if (Array.isArray(response)) {
      soldBooks.value = response
    } else if (response && response.code === 200 && response.data) {
      soldBooks.value = response.data
    } else {
      console.error('获取已售出书籍失败: 返回格式不正确', response)
      soldBooks.value = []
    }
    
    console.log('获取已售出书籍成功:', soldBooks.value)
  } catch (error) {
    console.error('获取已售出书籍失败:', error)
    soldBooks.value = []
  }
}

const fetchPurchasedBooks = async () => {
  try {
    console.log('开始获取已购买书籍');
    // 调用API获取用户已购买的书籍
    const response = await api.book.getLookBought();
    console.log('已购买书籍原始响应:', response);
    
    // 处理响应数据
    if (Array.isArray(response.books)) {
      purchasedBooks.value = response.books;
      console.log('已购买书籍(从books数组):', purchasedBooks.value);
    } else if (response && response.books) {
      purchasedBooks.value = response.books;
      console.log('已购买书籍(从response.books):', purchasedBooks.value);
    } else {
      console.error('获取已购买书籍失败: 返回格式不正确', response);
      purchasedBooks.value = [];
    }
    
    // 添加缺失的字段
    purchasedBooks.value = purchasedBooks.value.map(book => {
      // 确保每本书都有book_id字段
      if (!book.book_id && book.id) {
        book.book_id = book.id;
      }
      return book;
    });
    
    console.log('处理后的已购买书籍:', purchasedBooks.value);
  } catch (error) {
    console.error('获取已购买书籍失败:', error);
    purchasedBooks.value = [];
  }
}

const fetchRemovedBooks = async () => {
  try {
    // 调用API获取用户已下架的书籍
    const response = await api.book.getMyBooks({ status: 'removed' })
    
    // 处理响应数据
    if (Array.isArray(response)) {
      removedBooks.value = response
    } else if (response && response.code === 200 && response.data) {
      removedBooks.value = response.data
    } else {
      console.error('获取已下架书籍失败: 返回格式不正确', response)
      removedBooks.value = []
    }
    
    console.log('获取已下架书籍成功:', removedBooks.value)
  } catch (error) {
    console.error('获取已下架书籍失败:', error)
    removedBooks.value = []
  }
}

const formatDate = (date) => {
  if (!date) return '暂无信息';
  
  try {
    // 处理字符串日期
    if (typeof date === 'string') {
      return new Date(date).toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
      });
    }
    
    // 处理Date对象
    if (date instanceof Date) {
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
      });
    }
    
    return '日期格式错误';
  } catch (error) {
    console.error('日期格式化错误:', error);
    return '日期格式错误';
  }
}

const getStatusText = (status) => {
  switch(status) {
    case 'active': return '在售'
    case 'reserved': return '已预订'
    case 'sold': return '已售出'
    case 'removed': return '已下架'
    default: return '未知状态'
  }
}

const publishNewBook = () => {
  router.push('/publish')
}

const editBook = (bookId) => {
  router.push(`/edit-book/${bookId}`)
}

const deleteBook = (bookId) => {
  bookToDelete.value = bookId
  showDeleteConfirm.value = true
}

const confirmDelete = async () => {
  try {
    // 调用API删除书籍
    await api.book.removeBook(bookToDelete.value)
    
    // 找到要下架的书籍完整数据
    const bookToRemove = publishedBooks.value.find(book => book.id === bookToDelete.value)
    
    // 从在售列表中移除该书籍
  publishedBooks.value = publishedBooks.value.filter(book => book.id !== bookToDelete.value)
    
    // 如果找到了书籍数据，将其添加到下架列表
    if (bookToRemove) {
      const removedBook = { ...bookToRemove, status: 'removed', removedDate: new Date() }
      removedBooks.value.unshift(removedBook) // 添加到列表顶部
    } else {
      // 如果没找到书籍数据，重新获取已下架书籍列表
      await fetchRemovedBooks()
    }
    
    // 关闭确认对话框
  showDeleteConfirm.value = false
  bookToDelete.value = null
    
  // 提示删除成功
    ElMessage.success('书籍已成功下架')
  } catch (error) {
    console.error('下架书籍失败:', error)
    ElMessage.error('下架失败，请重试')
  }
}

const viewBookDetails = (bookId) => {
  if (!bookId) {
    ElMessage.warning('无法获取书籍ID')
    return
  }
  router.push(`/book/${bookId}`)
}

const contactSeller = (seller) => {
  ElMessage.info(`即将联系卖家: ${seller}`)
  router.push({
    path: '/messages',
    query: { contact: seller }
  })
}

const contactBuyer = (buyer) => {
  ElMessage.info(`即将联系买家: ${buyer}`)
  router.push({
    path: '/messages',
    query: { contact: buyer }
  })
}

const removeFavorite = async (bookId) => {
  try {
    // 调用API取消收藏
    await api.book.toggleFavorite(bookId)
    
    // 从列表中移除该书籍
  favoriteBooks.value = favoriteBooks.value.filter(book => book.id !== bookId)
    console.log('取消收藏成功:', bookId)
  } catch (error) {
    console.error('取消收藏失败:', error)
    ElMessage.error('取消收藏失败，请重试')
  }
}

const getCoverUrl = (book) => {
  console.log('处理封面URL，封面数据:', book.cover);
  if (!book || !book.cover) {
    console.log('无封面数据，使用默认封面');
    return defaultCover;
  }
  
  try {
    // 检查是否为相对路径，添加基础URL
    if (typeof book.cover === 'string') {
      if (!book.cover.startsWith('http')) {
        // 对路径进行URL编码，确保特殊字符不会导致问题
        const encodedPath = book.cover.split('/').map(segment => encodeURIComponent(segment)).join('/');
        console.log('编码后的封面路径:', encodedPath);
        return `http://localhost:8080/${encodedPath}`;
      }
      return book.cover;
    }
    
    // 如果book.cover不是字符串，使用默认封面
    console.log('封面格式不正确，使用默认封面');
    return defaultCover;
  } catch (error) {
    console.error('处理封面URL时出错:', error);
    return defaultCover;
  }
}

const filteredBooks = computed(() => {
  switch (activeTab.value) {
    case 'selling':
      return publishedBooks.value.filter(book => book.status === 'active');
    case 'sold':
      return soldBooks.value;
    case 'purchased':
      return purchasedBooks.value;
    case 'removed':
      return removedBooks.value;
    case 'favorite':
      return favoriteBooks.value;
    default:
      return [];
  }
});

const getEmptyStateText = () => {
  const texts = {
    'selling': '在售书籍',
    'sold': '已售出书籍',
    'purchased': '已购买书籍',
    'removed': '已下架书籍',
    'favorite': '收藏书籍'
  }
  return texts[activeTab.value] || '书籍'
}

const changeTab = (tab) => {
  activeTab.value = tab
  
  // 当切换到下架标签页时，刷新下架书籍数据
  if (tab === 'removed') {
    fetchRemovedBooks()
  }
  
  router.push({
    query: { tab }
  })
}

// 预加载当前标签页的所有封面
const preloadCovers = async () => {
  console.log('开始预加载当前标签页的封面');
  const books = filteredBooks.value;
  
  const promises = books.map(book => {
    const url = getCoverUrl(book);
    console.log('预加载封面:', url);
    return new Promise((resolve) => {
      const img = new Image();
      img.onload = () => {
        console.log('封面加载成功:', url);
        resolve();
      };
      img.onerror = (err) => {
        console.error('封面加载失败:', url, err);
        resolve(); // 即使失败也resolve，不阻塞流程
      };
      img.src = url;
    });
  });
  
  try {
    await Promise.all(promises);
    console.log('所有封面预加载完成');
  } catch (error) {
    console.error('预加载封面过程中发生错误:', error);
  }
}

// 添加一个刷新方法
const reloadData = () => {
  // 重新加载数据
  isLoading.value = true;
  console.log('用户手动刷新数据');
  
  // 延迟100ms再刷新，确保UI更新
  setTimeout(() => {
    Promise.all([
      fetchPublishedBooks(),
      fetchFavoriteBooks(),
      fetchSoldBooks(),
      fetchPurchasedBooks(),
      fetchRemovedBooks()
    ]).then(() => {
      console.log('所有数据刷新完成');
      // 预加载封面
      return preloadCovers();
    }).finally(() => {
      isLoading.value = false;
      console.log('数据刷新完成，标签页:', activeTab.value);
    });
  }, 100);
}
</script>

<style scoped>
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

h1 {
  font-size: 1.8rem;
  color: #1f2937;
  margin-bottom: 1.5rem;
}

.user-actions {
  display: flex;
  gap: 1rem;
  margin-bottom: 2rem;
}

.btn-publish, .btn-transactions, .btn-reload {
  padding: 0.75rem 1.5rem;
  border-radius: 6px;
  font-weight: 500;
  text-decoration: none;
  transition: all 0.2s;
}

.btn-publish {
  background-color: #3b82f6;
  color: white;
}

.btn-publish:hover {
  background-color: #2563eb;
}

.btn-transactions {
  background-color: #f3f4f6;
  color: #4b5563;
  border: 1px solid #d1d5db;
}

.btn-transactions:hover {
  background-color: #e5e7eb;
}

.btn-reload {
  background-color: #10b981;
  color: white;
  border: none;
  cursor: pointer;
}

.btn-reload:hover {
  background-color: #059669;
}

.tabs {
  display: flex;
  border-bottom: 1px solid #e5e7eb;
  margin-bottom: 2rem;
}

.tab-btn {
  padding: 0.75rem 1.5rem;
  background: none;
  border: none;
  border-bottom: 2px solid transparent;
  font-size: 1rem;
  font-weight: 500;
  color: #6b7280;
  cursor: pointer;
  transition: all 0.2s;
}

.tab-btn:hover {
  color: #3b82f6;
}

.tab-btn.active {
  color: #3b82f6;
  border-bottom-color: #3b82f6;
}

.books-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 2rem;
}

.book-card {
  border-radius: 8px;
  overflow: hidden;
  background-color: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s, box-shadow 0.2s;
}

.book-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.book-cover {
  position: relative;
  height: 300px;
  overflow: hidden;
}

.book-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.book-card:hover .book-cover img {
  transform: scale(1.05);
}

.book-actions {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 1rem;
  background: linear-gradient(to top, rgba(0, 0, 0, 0.7), transparent);
  display: flex;
  gap: 0.5rem;
  opacity: 0;
  transition: opacity 0.3s;
}

.book-card:hover .book-actions {
  opacity: 1;
}

.book-actions button {
  flex: 1;
  padding: 0.5rem;
  border: none;
  border-radius: 4px;
  background-color: #3b82f6;
  color: white;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.2s;
}

.book-actions button:hover {
  background-color: #2563eb;
}

.book-actions button.delete {
  background-color: #ef4444;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.3rem;
}

.book-actions button.delete:hover {
  background-color: #dc2626;
}

.book-actions button.republish {
  background-color: #10b981;
}

.book-actions button.republish:hover {
  background-color: #059669;
}

.book-info {
  padding: 1rem;
}

.book-info h3 {
  margin: 0 0 0.5rem;
  font-size: 1.1rem;
  color: #1f2937;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.book-author {
  color: #6b7280;
  margin-bottom: 0.5rem;
  font-size: 0.9rem;
}

.book-price {
  font-weight: bold;
  color: #ef4444;
}

.book-status {
  font-size: 0.8rem;
  color: #10b981;
  margin-top: 0.5rem;
}

.empty-state {
  text-align: center;
  padding: 4rem 2rem;
  background-color: #f9fafb;
  border-radius: 8px;
}

.empty-icon {
  font-size: 3rem;
  margin-bottom: 1.5rem;
}

.empty-state h3 {
  margin-bottom: 1rem;
  color: #1f2937;
}

.empty-state p {
  color: #6b7280;
  margin-bottom: 1.5rem;
}

.empty-actions {
  display: flex;
  justify-content: center;
  gap: 1rem;
}

.btn-primary, .btn-secondary {
  padding: 0.75rem 1.5rem;
  border-radius: 6px;
  font-weight: 500;
  text-decoration: none;
}

.btn-primary {
  background-color: #3b82f6;
  color: white;
}

.btn-primary:hover {
  background-color: #2563eb;
}

.btn-secondary {
  background-color: #f3f4f6;
  color: #4b5563;
  border: 1px solid #d1d5db;
}

.btn-secondary:hover {
  background-color: #e5e7eb;
}

@media (max-width: 768px) {
  .container {
    padding: 1rem;
  }
  
  .books-grid {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    gap: 1rem;
  }
  
  .book-cover {
    height: 220px;
  }
  
  .tabs {
    overflow-x: auto;
  }
  
  .tab-btn {
    padding: 0.75rem 1rem;
    white-space: nowrap;
  }
  
  .user-actions {
    flex-direction: column;
  }
}

.confirm-dialog {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog-content {
  background-color: white;
  border-radius: 8px;
  padding: 2rem;
  width: 90%;
  max-width: 500px;
}

.dialog-content h3 {
  margin-top: 0;
  margin-bottom: 1rem;
  color: #1f2937;
}

.dialog-content p {
  margin-bottom: 1.5rem;
  color: #4b5563;
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
}

.btn-cancel, .btn-confirm {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 4px;
  font-weight: 500;
  cursor: pointer;
}

.btn-cancel {
  background-color: #f3f4f6;
  color: #4b5563;
}

.btn-cancel:hover {
  background-color: #e5e7eb;
}

.btn-confirm {
  background-color: #ef4444;
  color: white;
}

.btn-confirm:hover {
  background-color: #dc2626;
}

/* 淡入淡出过渡效果 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.star-icon {
  color: #F7BA2A;
  font-size: 1rem;
}
</style> 